package com.dycx.payment.service.impl;


import com.dycx.common.enums.SourceEnum;
import com.dycx.payment.dto.PaymentOrderDTO;
import com.dycx.payment.service.JsapiPayService;
import com.dycx.payment.service.PaymentOrderService;
import com.dycx.system.service.ConfigService;
import com.dycx.system.vo.SystemConfig;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 文章关键字(PaymentOrder)表服务实现类
 *
 * @author wuzongbin
 * @since 2024-01-16 09:57:09
 */

@Service
@AllArgsConstructor
@Slf4j
public class JsapiPayImpl implements JsapiPayService {
    private ConfigService configService;
    private PaymentOrderService paymentOrderService;

    /**
     * jsapi支付
     *
     * @param dto
     * @return
     */
    @Override
    public PrepayWithRequestPaymentResponse jsapiPay(PaymentOrderDTO dto) {
        String outTradeNo = paymentOrderService.create(dto);
        SystemConfig sysConfig = configService.getSystemConfig();

        RSAAutoCertificateConfig config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(sysConfig.getWxPayMerchantId())
                        .privateKeyFromPath(sysConfig.getWxPayPrivateKeyPath())
                        .merchantSerialNumber(sysConfig.getWxPayMerchantSerialNumber())
                        .apiV3Key(sysConfig.getWxPayApiV3Key())
                        .build();
        // 构建service
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
        PrepayRequest request = new PrepayRequest();

        Amount amount = new Amount();
        amount.setTotal(dto.getAmount());
        request.setAmount(amount);

        Payer payer = new Payer();
        payer.setOpenid(dto.getOpenId());
        request.setPayer(payer);

        if (SourceEnum.WX_MP.getCode().equals(dto.getSource())) {
            request.setAppid(sysConfig.getWxMpAppId());
        } else if (SourceEnum.WX_MINI_APP.getCode().equals(dto.getSource())) {
            request.setAppid(sysConfig.getWxMiniAppId());
        }

        request.setMchid(sysConfig.getWxPayMerchantId());
        request.setDescription(dto.getDescription());
        request.setNotifyUrl(sysConfig.getWxPayNotifyUrl());
        request.setOutTradeNo(outTradeNo);
        return service.prepayWithRequestPayment(request);
    }

}

